﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using AMail.Common.Interfaces.Data;

namespace AMail.Modules.Data.Actions
{
  public class ModifyMessagePropertyAction : IMailAction
  {
    private IMailMessage message;
    private string propertyName;
    private object previousValue;

    public ModifyMessagePropertyAction(IMailMessage message, string propertyName, object previousValue)
    {
      this.message = message;
      this.propertyName = propertyName;
      this.previousValue = previousValue;
    }

    #region IMailAction Members

    public void Commit(IMailArchiver archiver)
    {
    }

    public void Undo()
    {
      this.NewValue = this.previousValue;
    }

    #endregion

    private object NewValue
    {
      get
      {
        PropertyInfo property = typeof(IMailMessage).GetProperty(propertyName);
        return property.GetValue(this.message, null);
      }
      set
      {
        PropertyInfo property = typeof(IMailMessage).GetProperty(propertyName);
        property.SetValue(this.message, this.previousValue, null);
      }
    }

    public override string ToString()
    {
      return string.Format("Message '{0}', property '{1}' changed from '{2}' to '{3}'",
        this.message.Subject,
        this.propertyName,
        this.previousValue,
        this.NewValue);
    }
  }
}
